<template>
  <div>
    <el-row>
      <el-col :span="5">
        <div class="tree">
          <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
          <el-tree @node-click="handler" class="filter-tree" :data="empData" :props="defaultProps"
            :filter-node-method="filterNode" ref="tree"></el-tree>
        </div>
      </el-col>
      <el-col :span="19">
        <div>
          <el-row>
            <el-col :span="4">
              <el-button style="font-size: 15px" type="primary" @click="showChart('tsp')" :class="{active: activeButton === 'tsp'}">tsp</el-button>
            </el-col>
            <el-col :span="4">
              <el-button style="font-size: 15px" type="primary" @click="showChart('pm10')":class="{active: activeButton === 'pm10'}">pm10</el-button>
            </el-col>
            <el-col :span="4">
              <el-button style="font-size: 15px" type="primary" @click="showChart('pm25')":class="{active: activeButton === 'pm25'}">pm2.5</el-button>
            </el-col>
            <el-col :span="4">
              <el-button style="font-size: 15px" type="primary" @click="showChart('temperature')":class="{active: activeButton === 'temperature'}">温度</el-button>
            </el-col>
            <el-col :span="4">
              <el-button style="font-size: 15px" type="primary" @click="showChart('humidity')":class="{active: activeButton === 'humidity'}">湿度</el-button>
            </el-col>
          </el-row>
        </div>
        <div id="plot-container"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { get } from '@/utils/request'
import { Line } from '@antv/g2plot';
import moment from 'moment'

export default {
  data() {
    return {
      filterText: '',
      empData: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        timer: null,
        linePlot: null
      },
      params: {
        page: 1, // 新增 page 参数
        pageSize: 20, // 新增 pageSize 参数
        device_id: 0,
      },
      monitorData: [],
      currentIndicator: '', // 用于记录当前展示的指标
      yAxisConfigs: {
        tsp: { min: 0, max: 80, tickInterval: 20 },
        pm10: { min: 0, max: 120, tickInterval: 30 },
        pm25: { min: 0, max: 80, tickInterval: 20 },
        temperature: { min: 0, max: 30, tickInterval: 10 },
        humidity: { min: 0, max: 80, tickInterval: 20 }
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    handler(val) {
      if (!val.children) {
        // 清除旧的定时器
        if (this.timer) {
          clearInterval(this.timer)
          this.timer = null
        }
        this.params.device_id = val.id;
        this.getMonitor()
        // 设置定时器每5秒获取一次数据
        this.timer = setInterval(() => {
          this.getMonitor()
        }, 5000)
        this.currentIndicator = 'tsp'
        
        this.renderChart()
      }
    },
      
    async getMonitor() {
      try {
        const res = await get('/monitor/pageQueryTodayData', this.params)
        this.monitorData = res.data?.list || [];
        this.monitorData.forEach((item, index, arr) => {
          arr[0].temperature = 15.4;
          arr[0].tsp = 60;
          arr[0].pm10 = 90;
          arr[0].pm25 = 30;
          arr[0].humidity = 50;
        })
        console.log('获取到的数据:', this.monitorData) // 添加日志输出
        this.renderChart()
      } catch (error) {
        console.error('获取数据失败', error)
      }
    },
    showChart(indicator) {
      this.currentIndicator = indicator
      this.renderChart()
    },
    renderChart() {
      const data = this.monitorData.map((item) => ({
        time: moment(item.insert_time).format('HH:mm'),
        value: item[this.currentIndicator]
      }));
      const yAxisConfig = this.yAxisConfigs[this.currentIndicator];
      if (!this.linePlot) {
        // 初始化图表
        this.linePlot = new Line('plot-container', {
          data,
          xField: 'time',
          yField: 'value',
          title: {
            text: this.currentIndicator === 'pm25'? 'pm2.5' : this.currentIndicator
          },
          tooltip: {
            formatter: (obj) => ({
              name: obj.name,
              value: `${obj.value}`
            })
          },
          yAxis: {
            min: yAxisConfig.min,
            max: yAxisConfig.max,
            tickInterval: yAxisConfig.tickInterval,
            label: {
              formatter: (val) => val.toString()
            }
          }
        });
        this.linePlot.render();
      } else {
        // 更新图表数据和配置
        this.linePlot.update({
          data,
          title: {
            text: this.currentIndicator === 'pm25'? 'pm2.5' : this.currentIndicator
          },
          yAxis: {
            min: yAxisConfig.min,
            max: yAxisConfig.max,
            tickInterval: yAxisConfig.tickInterval,
            label: {
              formatter: (val) => val.toString()
            }
          }
        });
        this.linePlot.render();
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    async getEmpData() {
      const res = await get('/dashboard/findEngineerDeviceTree')
      this.empData = res.data
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    // 销毁图表实例
    if (this.linePlot) {
      this.linePlot.destroy()
      this.linePlot = null
    }
  },
  created() {
    this.getEmpData()
  }
}
</script>    
<style>
.el-button {
  border: none;
  background-color: transparent;
  color: inherit;
  padding: 0;
  margin-right: 30px;
}
.el-button.active {
  color: green;
  border-bottom: 40px solid green;
}
/* 新增图表容器样式 */
#plot-container {
  margin-top: 30px;  /* 增加上边距 */
  height: 500px;     /* 可选：给图表容器固定高度 */
}
</style>